package com.punch.course.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.punch.common.vo.system.category.CategoryTreeVO;

import com.punch.course.mapper.CourseCategoryMapper;
import com.punch.course.model.CourseCategroy;
import com.punch.course.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * CategoryServiceImpl-
 *
 * @author wujj
 * @version 1.0.0
 * @since 2020/7/24 15:29
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategroy> implements CategoryService {

    @Override
    public List<CategoryTreeVO> treeCategory() {
        List<CourseCategroy> list = list();
        Map<Long, List<CourseCategroy>> categoryMap = list.stream().collect(Collectors.groupingBy(CourseCategroy::getParentId));
        return handlerCategoryTree(categoryMap, 0L);
    }

    /**
     * 根据课程分类名称查询课程分类id
     *
     * @param categoryName 课程分了名称
     * @return
     */
    @Override
    public List<CourseCategroy> findCategoryIdByName(String categoryName) {
        QueryWrapper<CourseCategroy> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CourseCategroy::getCategoryName,categoryName);
        return this.baseMapper.selectList(queryWrapper);
    }


    /**
     * 迭代处理菜单
     *
     * @param categoryMap 数据库数据
     * @param pid         父id
     * @author wujj
     * @since 2020/6/9 18:25
     */
    private List<CategoryTreeVO> handlerCategoryTree(Map<Long, List<CourseCategroy>> categoryMap, Long pid) {
        List<CategoryTreeVO> retList = new ArrayList<>();
        List<CourseCategroy> courseCategroyList = categoryMap.get(pid);
        if (CollUtil.isEmpty(courseCategroyList)) {
            return retList;
        }
        courseCategroyList.forEach(courseCategroy -> {
            CategoryTreeVO categoryTreeVO = new CategoryTreeVO();
            categoryTreeVO.setCategoryId(courseCategroy.getId());
            categoryTreeVO.setCategoryName(courseCategroy.getCategoryName());
            retList.add(categoryTreeVO);
            //查找子节点
            if (categoryMap.get(courseCategroy.getId()) != null) {
                categoryTreeVO.setChildList(handlerCategoryTree(categoryMap, courseCategroy.getId()));
            }
        });
        return retList;
    }


}
